package com.dylan.netty.nio.socket;

import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author zhangshaojian
 * @date 2022/8/10 9:22
 */
@Slf4j
public class Server {
    public static void main(String[] args) {
        singleThread();
    }

    private static void singleThread() {
        try (
                ServerSocketChannel channel = ServerSocketChannel.open();
                Selector selector = Selector.open()
        ) {
            log.info("开启服务器=={}", channel);
            channel.bind(new InetSocketAddress(8888));
            channel.configureBlocking(false);
            channel.register(selector, SelectionKey.OP_ACCEPT);
            log.info("服务器绑定端口=={}", channel);
            while (true) {
                selector.select();
                Set<SelectionKey> keys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = keys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isAcceptable()) {
                        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                        SocketChannel socketChannel = serverSocketChannel.accept();
                        log.info("客户端接入了！！" + key.channel());
                        socketChannel.configureBlocking(false);
                        socketChannel.register(selector, SelectionKey.OP_READ);
                        log.info("注册选择器，可以读咯！！！！");
                    } else if (key.isReadable()) {
                        SocketChannel readChannel = (SocketChannel) key.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        readChannel.read(buffer);
                        log.info("传来消息：{}", new String(buffer.array()));
                    }
                    iterator.remove();
                }
            }
        } catch (Exception ex) {
            log.error("服务器开小差咯！！！！", ex);
        }
    }
}
